const path = require('path');
const HtmlWebpackPlugin = require("html-webpack-plugin");
const glob = require('glob');
const resolve = (dir) => path.join(__dirname, dir);
const { VueLoaderPlugin } = require('vue-loader');
const WebpackPlugin = [ new VueLoaderPlugin() ];

function getEntry() {
  const entry = {};
  // 读取src目录所有page入口
  glob.sync('./src/pages/*/index.js')
    .forEach(function (filePath) {
      let name = filePath.match(/\/pages\/(.+)\/index.js/);
      name = name[1];
      entry[name] = filePath;

      WebpackPlugin.push(new HtmlWebpackPlugin({
        template: './public/index.html',
        filename: name + '.html',
        title: name + ' title',
        chunks: [ name ]
      }));
    });
  return entry;
}

module.exports = {
  entry: getEntry(),
  output: {
    filename: 'js/[name].bundle.js', // -[chunkhash]
    path: resolve('../dist'),
    clean: true,
  },
  resolve: {
    alias: {
      "@": resolve('../src'),
    },
  },
  plugins: WebpackPlugin,
  module: {
    rules: [
      {
        test: /\.css$/i,
        use: ['style-loader', 'css-loader'],
      },
      {
        test: /\.(png|svg|jpg|jpeg|gif)$/i,
        type: 'asset/resource',
      },
      {
        test: /\.(woff|woff2|eot|ttf|otf)$/i,
        type: 'asset/resource',
      },
      {
        test: /\.vue$/,
        exclude: /(node_modules|bower_components)/,
        use: ['vue-loader']
      },
    ],
  },
};
